package com.zhengyisky.service;

import com.zhengyisky.entity.*;
import com.zhengyisky.mapper.NewsMapper;
import com.zhengyisky.utils.FreemarkerUtil;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class NewsSerivce {

    @Autowired
    private NewsMapper newsMapper;

    public List<News> list() {
        return newsMapper.list();
    }

    public List<Type> typeList() {
        return newsMapper.typeList();
    }

    public void save(AddEntity addEntity) {
        News news = addEntity.getNews();
        newsMapper.saveNews(news);
        List<Chapter> chapterList = addEntity.getChapterList();
        for (Chapter chapter : chapterList) {
            chapter.setNewsId(news.getId());
            newsMapper.saveChapter(chapter);
        }
    }

    public Map listPage(QueryParam queryParam) {
        Integer count = newsMapper.count(queryParam);

        Integer index = (queryParam.getPage()-1)*queryParam.getSize();
        queryParam.setIndex(index);
        List<News> list = newsMapper.listPage(queryParam);

        Map map = new HashMap();
        map.put("list", list);
        map.put("count",count);
        return map;
    }

    public void pass(Integer id) throws TemplateException, IOException {
        newsMapper.pass(id);


        News news = newsMapper.findNewsById(id);
        List<Chapter> list = newsMapper.findChapterById(id);

        //生成静态页
        FreemarkerUtil freemarkerUtil = new FreemarkerUtil();

        HashMap<String,Object> map = new HashMap();
        map.put("news", news);
        map.put("list", list);
        freemarkerUtil.createHtml(map,"news","D:\\2112A\\nginx-1.26.1\\html\\new"+id+".html");
    }

    public void notPass(Integer id, String reason) {
        newsMapper.notPass(id, reason);
    }
}
